package com.libui.utils

import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import com.libbase.Weak
import com.libbase.utils.DensityUtils
import kotlin.math.abs

class SoftKeyboardUtils(
    activity: Activity,
    private val listener: OnSoftKeyboardChangeListener
) {
    interface OnSoftKeyboardChangeListener {
        fun onKeyboardShow(height: Int)
        fun onKeyboardHide(height: Int)
    }

    private val rootView: View? by Weak { activity.window.decorView }

    private var rootViewVisibleHeight: Int = 0

    init {
        rootView?.let {
            it.viewTreeObserver.addOnGlobalLayoutListener(object :
                ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    val windowDisplayFrame = Rect()
                    it.getWindowVisibleDisplayFrame(windowDisplayFrame)
                    val visibleHeight = windowDisplayFrame.height()

                    if (rootViewVisibleHeight == 0) {
                        rootViewVisibleHeight = visibleHeight
                        return
                    }

                    if (rootViewVisibleHeight == visibleHeight) {
                        return
                    }

                    val softKeyBoardHeight = rootViewVisibleHeight - visibleHeight

                    if (softKeyBoardHeight > 200) {
                        rootViewVisibleHeight = visibleHeight
                        listener.onKeyboardShow(DensityUtils.instance.px2dp(it.context, softKeyBoardHeight.toFloat()))

                        return
                    }

                    if (softKeyBoardHeight < -200) {
                        rootViewVisibleHeight = visibleHeight
                        listener.onKeyboardHide(DensityUtils.instance.px2dp(it.context, abs(softKeyBoardHeight.toFloat())))
                        return
                    }
                }
            })
        }
    }
}